package com.software.sqlite.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.*;

@Slf4j
public class FTPDownloadWithProgress {
    private FTPClient ftpClient = new FTPClient();
    public static String percentProgress="0%";
    public static long totalSize=0;
    public static long doneSize=0;
    /**
     * 完整下载验证方法
     */
    public static void main(String[] args) {
        try{
            // 配置FTP连接参数（需替换为实际值）
            String host = "10.0.0.36";
            int port = 27;
            String user = "shipnet";
            String password = "shipnet123!@#321";
            String remoteFile = "Manhaton.mp4";
            String localFile = "/Volumes/work/Other/test/Manhaton1.mp4";
            download(host,port,user,password,remoteFile,localFile);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(FTPDownloadWithProgress.percentProgress);
        }

    }

    public static boolean download(String host, int port,String user,String password,String remoteFile,String localFile) {
        boolean flag = false;
        FTPDownloadWithProgress downloader = new FTPDownloadWithProgress();
        // 配置FTP连接参数（需替换为实际值）
        try {
            // 连接服务器
            log.info("Connecting to FTP server...");
            downloader.connect(host, port, user, password);

            // 执行下载
            log.info("Starting download...");
            flag=downloader.downloadFile(remoteFile, localFile);
            if(flag){
                log.info("Download completed successfully!");
            }else{
                log.error("Download failed!");
            }

        } catch (IOException e) {
            log.error("Error during download:");
            e.printStackTrace();
        } finally {
            // 确保断开连接
            try {
                downloader.disconnect();
            } catch (IOException e) {
                log.error("Error disconnecting:");
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 连接FTP服务器
     */
    public void connect(String host, int port, String user, String pass) throws IOException {
        ftpClient.connect(host, port);
        if (!ftpClient.login(user, pass)) {
            throw new IOException("Login failed");
        }
        log.info("Connected to " + host);
    }

    /**
     * 执行文件下载（包含进度显示）
     */
    public boolean downloadFile(String remoteFile, String localFile) throws IOException {
        boolean flag = false;
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        // 获取远程文件大小
        long remoteSize = ftpClient.listFiles(remoteFile)[0].getSize();
        totalSize=remoteSize;
        if (remoteSize == -1) {
            throw new FileNotFoundException("Remote file not found: " + remoteFile);
        }

        // 检查本地文件状态
        File local = new File(localFile);
        long localSize = local.exists() ? local.length() : 0;

        if (localSize == remoteSize) {
            log.info("File already exists with complete size.");
            percentProgress="100.00%";
            doneSize=remoteSize;
            flag=true;
            return flag;
        } else if (localSize > 0) {
            String result=String.format("Resuming download from %d/%d bytes (%.1f%%)\n", localSize, remoteSize, (localSize * 100.0 / remoteSize));
            log.info(result);
        }

        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(local, localSize > 0))) {
            // 设置断点续传
            ftpClient.setRestartOffset(localSize);
            InputStream is = ftpClient.retrieveFileStream(remoteFile);

            byte[] buffer = new byte[4096];
            int bytesRead;
            long totalRead = localSize;

            // 下载循环
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
                totalRead += bytesRead;
                // 实时更新进度
                printProgress(totalRead, remoteSize);
            }

            is.close();
            if (!ftpClient.completePendingCommand()) {
                throw new IOException("Download verification failed");
            }
        }
        flag=true;
        return flag;
    }

    /**
     * 进度显示方法
     */
    private void printProgress(long current, long total) {
        double percent = (current * 100.0) / total;
        totalSize=total;
        doneSize=current;
        percentProgress=String.format("%.2f%%", percent);
        System.out.printf("\rProgress: %.2f%% (%d/%d bytes)", percent, current, total);
//        String result=String.format("Progress: %.2f%% (%d/%d bytes)", percent, current, total);
//        log.info(result);
    }

    /**
     * 断开连接
     */
    public void disconnect() throws IOException {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
            log.info("Disconnected from server");
        }
    }
}
